from flask import current_app

from xtoad.models import User, db
from xtoad.schema.user import UserSchema


class UserService:

    userSchema = None

    def __init__(self):
        self.userSchema = UserSchema()

    def add(self, data):
        user = self.userSchema.load(data)
        user.hash_password()
        user.add()
        current_app.logger.info('测试logging')
        print("add user")

        return self.userSchema.dump(user)

    def delete(self, id):
        user = User.query.get(id)
        user.delete()
        print("delete user")

        return True

    def get(self, id):
        user = User.query.get(id)
        print("get user:", id)

        return self.userSchema.dump(user)

    def get_by_loginname(self, loginname):
        user = User.query.filter_by(nick_name=loginname).first()
        print("get user:", id)
        return user

    def get_all(self):
        users = User.query.all()
        print("get users:", self.userSchema.dump(users, many=True))

        return self.userSchema.dump(users, many=True)

    def add_all(self, users):
        users = self.userSchema.load(users, many=True)
        for user in users:
            user.user.hash_password()
        db.session.bulk_insert_mappings(User, users)
        db.session.commit()

        print("add users:", self.userSchema.dump(users, many=True))

        return self.userSchema.dump(users, many=True)

